/**
 * $Id: GraphEditor.java,v 1.2 2012/11/20 09:08:09 gaudenz Exp $ Copyright (c)
 * 2006-2012, JGraph Ltd
 */
package com.mxgraph.examples.swing;

//import Thread2;
import com.mxgraph.examples.swing.editor.ArrayListofVisibleItem;
import com.mxgraph.examples.swing.editor.BasicGraphEditor;
import com.mxgraph.examples.swing.editor.DatabaseConnectivity;
import com.mxgraph.examples.swing.editor.EditorActions;
import com.mxgraph.examples.swing.editor.EditorActions.SaveAction;
import com.mxgraph.examples.swing.editor.EditorMenuBar;
import com.mxgraph.examples.swing.editor.EditorPalette;
import com.mxgraph.examples.swing.editor.PropertyForm;
import com.mxgraph.io.mxCodec;
import com.mxgraph.model.mxCell;
import com.mxgraph.model.mxGeometry;
import com.mxgraph.model.mxICell;
import com.mxgraph.model.mxIGraphModel;
import com.mxgraph.swing.mxGraphComponent;
import com.mxgraph.swing.util.mxSwingConstants;
import com.mxgraph.util.mxConstants;
import com.mxgraph.util.mxPoint;
import com.mxgraph.util.mxResources;
import com.mxgraph.util.mxUtils;
import com.mxgraph.view.mxCellState;
import com.mxgraph.view.mxGraph;
import java.awt.Color;
import java.awt.Dimension;
import java.util.Iterator;
import java.util.List;
//import java.awt.List;
import java.awt.Point;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.sql.Statement;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.UIManager;

import org.snmp4j.smi.IpAddress;
import org.w3c.dom.Document;

public class GraphEditor extends BasicGraphEditor {

    //public  ArrayList<String> al = new ArrayList<String>();
    static JMenuBar GraphMenuBar;
    //static String ipAddress = "10.250.250.81";
    static String ipAddress1;
    static JFrame name2;
    String r;
    Thread t;
    /**
     *
     */
    private static final long serialVersionUID = -4601740824088314699L;

    public GraphEditor(JFrame name, String ipAddress) {
        //super();
        super(name);
        name2 = name;
        ipAddress1 = ipAddress;

        //t=new Thread(this);
        //this.ipAddress=ip;
        //t.start();
        //name = name2;
        //System.out.println("hfgjdhf");
    }
    /**
     * Holds the shared number formatter.
     *
     * @see NumberFormat#getInstance()
     */
    public static final NumberFormat numberFormat = NumberFormat.getInstance();
    /**
     * Holds the URL for the icon to be used as a handle for creating new
     * connections. This is currently unused.
     */
    public static URL url = null;

    // GraphEditor.class.getResource("/com/mxgraph/examples/swing/images/connector.gif");
    public GraphEditor() {
        this("PacketFence Network Management System", new CustomGraphComponent(
                new CustomGraph()));
    }

    /**
     * fghfg
     *
     */
    public GraphEditor(String appTitle, mxGraphComponent component) {
        super(appTitle, component);
        final mxGraph graph = graphComponent.getGraph();
        component.setConnectable(false);// **********For disabling the Cloning
        // Feature

        // Creates the shapes palette
        // EditorPalette shapesPalette =
        // insertPalette(mxResources.get("shapes"));
        EditorPalette imagesPalette = insertPalette(mxResources.get("images"));

        // EditorPalette symbolsPalette =
        // insertPalette(mxResources.get("symbols"));
        // Sets the edge template to be used for creating new edges if an edge
        // is clicked in the shape palette
        // System.out.println("imagesPalette");
        imagesPalette
                .addTemplate(
                "Router",
                new ImageIcon(
                GraphEditor.class
                .getResource("/com/mxgraph/examples/swing/images/RouterGreen.png")),
                "image;image=/com/mxgraph/examples/swing/images/RouterGreen.png",
                50, 50, "Router");
        imagesPalette
                .addTemplate(
                "Switch",
                new ImageIcon(
                GraphEditor.class
                .getResource("/com/mxgraph/examples/swing/images/SwitchIcon.png")),
                "image;image=/com/mxgraph/examples/swing/images/SwitchIcon.png",
                50, 50, "Switch");
        imagesPalette
                .addTemplate(
                "Cloud",
                new ImageIcon(
                GraphEditor.class
                .getResource("/com/mxgraph/examples/swing/images/CloudIcon.png")),
                "image;image=/com/mxgraph/examples/swing/images/CloudIcon.png",
                50, 50, "Cloud");
        /*imagesPalette
         .addTemplate(
         "User",
         new ImageIcon(
         GraphEditor.class
         .getResource("/com/mxgraph/examples/swing/images/dude3.png")),
         "roundImage;image=/com/mxgraph/examples/swing/images/dude3.png",
         50, 50, "User");*/
        imagesPalette
                .addTemplate(
                "Firewall",
                new ImageIcon(
                GraphEditor.class
                .getResource("/com/mxgraph/examples/swing/images/FirewallIcon.png")),
                "roundImage;image=/com/mxgraph/examples/swing/images/FirewallIcon.png",
                50, 50, "Firewall");
        imagesPalette
                .addTemplate(
                "Printer",
                new ImageIcon(
                GraphEditor.class
                .getResource("/com/mxgraph/examples/swing/images/PrinterGreen.png")),
                "image;image=/com/mxgraph/examples/swing/images/PrinterGreen.png",
                50, 50, "Printer");
        imagesPalette
                .addTemplate(
                "Server",
                new ImageIcon(
                GraphEditor.class
                .getResource("/com/mxgraph/examples/swing/images/ServerGreen.png")),
                "image;image=/com/mxgraph/examples/swing/images/ServerGreen.png",
                50, 50, "Server");
        imagesPalette
                .addTemplate(
                "Workplace",
                new ImageIcon(
                GraphEditor.class
                .getResource("/com/mxgraph/examples/swing/images/workplace.png")),
                "image;image=/com/mxgraph/examples/swing/images/workplace.png",
                70, 70, "Workplace");
        /*
         * imagesPalette.addTemplate( "Earth", new ImageIcon(
         * GraphEditor.class.getResource
         * ("/com/mxgraph/examples/swing/images/earth.png")),
         * "image;image=/com/mxgraph/examples/swing/images/earth.png", 50, 50,
         * "Earth");
         */
    }

    /**
     *
     */
    public static class CustomGraphComponent extends mxGraphComponent {

        /**
         *
         */
        private static final long serialVersionUID = -6833603133512882012L;

        /**
         *
         * @param graph
         */
        public CustomGraphComponent(mxGraph graph) {
            super(graph);
            //graph.
            graph.setCellsEditable(false);
            // graph.isEdgeLabelsMovable();
            graph.setCellsResizable(true);
            //graph.isCellsSelectable();

            //graph.sets
            setPageVisible(false);
            setGridVisible(false);
            setToolTips(true);
            //super.setCellsEditable(false); }
            // graph.setCellsDisconnectable(false);
            getConnectionHandler().setCreateTarget(true);
            // Loads the default stylesheet from an external file
            mxCodec codec = new mxCodec();
            Document doc = mxUtils.loadDocument(GraphEditor.class.getResource(
                    "/com/mxgraph/examples/swing/resources/default-style.xml")
                    .toString());
            System.out.println(doc);
            codec.decode(doc.getDocumentElement(), graph.getStylesheet());
            // Sets the background to white
            getViewport().setOpaque(true);
            getViewport().setBackground(Color.WHITE);
        }

        /*public  boolean isCellsSelectable()
         {
         mxCell model=null;
         if (model.isEdge())
         {
         return false;
         }

         return isCellsSelectable();
         }*/
        /**
         * Overrides drop behaviour to set the cell style if the target is not a
         * valid drop target and the cells are of the same type (eg. both
         * vertices or both edges).
         */
        public Object[] importCells(Object[] cells, double dx, double dy,
                Object target, Point location) {
            if (target == null && cells.length == 1 && location != null) {
                target = getCellAt(location.x, location.y);
                if (target instanceof mxICell && cells[0] instanceof mxICell) {
                    mxICell targetCell = (mxICell) target;
                    mxICell dropCell = (mxICell) cells[0];
                    if (targetCell.isVertex() == dropCell.isVertex()
                            || targetCell.isEdge() == dropCell.isEdge()) {
                        mxIGraphModel model = graph.getModel();
                        model.setStyle(target, model.getStyle(cells[0]));
                        graph.setSelectionCell(target);
                        return null;
                    }
                }
            }
            mxCell cellType = (mxCell) cells[0];
            if (((String) cellType.getValue()).equals("Cloud")) {
                return super.importCells(cells, dx, dy, target, location);
            } else {
                PropertyForm popupDrop = new PropertyForm((String) cellType.getValue(), graph, dx, dy, null);
                popupDrop.setVisible(true);

                //return super.importCells(cells, dx, dy, target, location);
                return null;
            }
        }
    }

    /**
     * A graph that creates new edges from a given template edge.
     */
    public static class CustomGraph extends mxGraph {

        @Override
        public void setCellsEditable(boolean bln) {

            super.setCellsEditable(false);
            super.setCellsResizable(true);
        }
        /* 
         * @Override public void setCellsCloneable(boolean bln) {
         * 
         * super.setCellsCloneable(bln); }
         * 
         * @Override public void setEnabled(boolean bln) {
         * super.setEnabled(bln); }
         */
        /**
         * Holds the edge to be used as a template for inserting new edges.
         */
        protected Object edgeTemplate;

        /**
         * Custom graph that defines the alternate edge style to be used when
         * the middle control point of edges is double clicked (flipped).
         */
        public CustomGraph() {
            setAlternateEdgeStyle("edgeStyle=mxEdgeStyle.ElbowConnector;elbow=vertical");
        }

        /**
         * Sets the edge template to be used to inserting edges.
         */
        public void setEdgeTemplate(Object template) {
            edgeTemplate = template;
        }

        /**
         * Prints out some useful information about the cell in the tooltip.
         */
        public String getToolTipForCell(Object cell) {
            String tip = "<html>";
            mxGeometry geo = getModel().getGeometry(cell);
            mxCellState state = getView().getState(cell);
            try {
                String cellID = ((mxCell) cell).getId();
                String[] splitter = cellID.split("_");
                System.out.println(splitter[0]);
                System.out.println(ArrayListofVisibleItem.deviceReachability.get(splitter[1]));
                if (ArrayListofVisibleItem.deviceReachability.get(splitter[1]).equals("OK")) {

                    if (cellID.contains("Server")) {
                        String temp = (String) ArrayListofVisibleItem.serverClosedPort.get(splitter[1]);
                        //if
try{
                        if (temp.isEmpty() || temp.equals(null)) {
                            tip += "<font  color=\"green\">System Status: OK<br>System ID: " + cellID + ""
                                    + "<br>Unvailable Services:" + ArrayListofVisibleItem.serverClosedPort.get(splitter[1]);

                            tip += "<br> "
                                    + "Available Services:" + ArrayListofVisibleItem.serverOpenPort.get(splitter[1]);
                        } else {
                            tip += "<font  color=\"orange\">System Status: OK<br>System ID: " + cellID + ""
                                    + "<br>Unvailable Services:" + ArrayListofVisibleItem.serverClosedPort.get(splitter[1]);

                            tip += "<br> "
                                    + "Available Services:" + ArrayListofVisibleItem.serverOpenPort.get(splitter[1]);
                        }
}catch(Exception e){}
                    } else {
                        tip += "<font  color=\"green\">System Status: OK<br>System ID: " + cellID + " ";
                    }
                } else {
                    tip += "<font  color=\"red\">System Status: CRITICAL<br>System ID: " + cellID + " ";
                }
                if (getModel().isEdge(cell)) {
                    /*  tip += "points={";
                     if (geo != null) {
                     List<mxPoint> points = geo.getPoints();
                     if (points != null) {
                     Iterator<mxPoint> it = points.iterator();
                     while (it.hasNext()) {
                     mxPoint point = it.next();
                     tip += "[x=" + numberFormat.format(point.getX())
                     + ",y=" + numberFormat.format(point.getY())
                     + "],";
                     }
                     tip = tip.substring(0, tip.length() - 1);
                     }
                     }

                     tip += "}<br>";
                     tip += "absPoints={";

                     if (state != null) {

                     for (int i = 0; i < state.getAbsolutePointCount(); i++) {
                     mxPoint point = state.getAbsolutePoint(i);
                     tip += "[x=" + numberFormat.format(point.getX())
                     + ",y=" + numberFormat.format(point.getY())
                     + "],";
                     }

                     tip = tip.substring(0, tip.length() - 1);
                     }

                     tip += "}";*/
                } else {
                    tip += "<br> System Status:" + ArrayListofVisibleItem.deviceRTTHashMap.get(splitter[1]);







                    /*
                     tip += "geo=[";

                     if (geo != null) {
                     tip += "x=" + numberFormat.format(geo.getX()) + ",y="
                     + numberFormat.format(geo.getY()) + ",width="
                     + numberFormat.format(geo.getWidth()) + ",height="
                     + numberFormat.format(geo.getHeight());
                     }

                     tip += "]<br>";
                     tip += "state=[";

                     if (state != null) {
                     tip += "x=" + numberFormat.format(state.getX()) + ",y="
                     + numberFormat.format(state.getY()) + ",width="
                     + numberFormat.format(state.getWidth())
                     + ",height="
                     + numberFormat.format(state.getHeight());
                     }

                     tip += "]";*/
                }

                mxPoint trans = getView().getTranslate();

                // tip += "<br>scale=" + numberFormat.format(getView().getScale())
                //        + ", translate=[x=" + numberFormat.format(trans.getX())
                //       + ",y=" + numberFormat.format(trans.getY()) + "]";
                tip += "</font></html>";
            } catch (Exception e) {
                e.printStackTrace();
            }
            return tip;
        }

        /**
         * Overrides the method to use the currently selected edge template for
         * new edges.
         *
         * @param graph
         * @param parent
         * @param id
         * @param value
         * @param source
         * @param target
         * @param style
         * @return
         */
        public Object createEdge(Object parent, String id, Object value,
                Object source, Object target, String style) {
            if (edgeTemplate != null) {
                mxCell edge = (mxCell) cloneCells(new Object[]{edgeTemplate})[0];
                edge.setId(id);
                return edge;
            }
            // mxGraphActions.getDeleteAction;
            // **********The Null vale will not create any edge.
            // return null;
            return super.createEdge(parent, id, value, source, target, style);
        }
    }

    /**
     *
     * @param args
     */
    /**
     * public static void main(String[] args) {
     *
     * ArrayList al = new ArrayList();
     *
     * //GraphEditor ob=new GraphEditor(h); //System.out.println("main");
     *
     * try {
     * UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }
     * catch (Exception e1) { // System.out.println("Hello"); //
     * e1.printStackTrace(); }
     *
     * mxSwingConstants.SHADOW_COLOR = Color.LIGHT_GRAY;
     * mxConstants.W3C_SHADOWCOLOR = "#D3D3D3"; GraphEditor editor = new
     * GraphEditor(); GraphMenuBar = new EditorMenuBar(editor);
     * //GraphMenuBar.getcom final JFrame guiFrame =
     * editor.createFrame((GraphMenuBar)); //mxGraph graphForThread =
     * editor.graphComponent.getGraph(); //graphForThread.get
     * guiFrame.setDefaultCloseOperation(guiFrame.DO_NOTHING_ON_CLOSE); //
     * editor.createFrame(new EditorMenuBar(editor)).setVisible(true);
     * guiFrame.addWindowListener(new WindowAdapter() { public void
     * windowClosing(WindowEvent e) {
     *
     *
     * //int confirmed = JOptionPane.showConfirmDialog(null, //	"Are you want
     * to save changes?", //	"Save Changes Message Box",
     * JOptionPane.YES_NO_OPTION);
     *
     * //if (confirmed == JOptionPane.NO_OPTION) { //	System.exit(0); //
     * xyz.setVisible(false); // editor.exit(editor); // dispose(); //} else {
     * GraphEditor editor = new GraphEditor(); EditorMenuBar GraphMenuBar1 = new
     * EditorMenuBar(editor); GraphMenuBar1.exitOption.doClick();
     * System.exit(0); //GraphMenuBar.po //BasicGraphEditor editor =new
     * BasicGraphEditor(); //EditorMenuBar trySave = new EditorMenuBar(); //
     * public void actionPerformed(ActionEvent e){ // BasicGraphEditor editor =
     * getEditor(e);
     *
     * // SaveAction exitSave = new SaveAction(true); //SaveAction save = new
     * SaveAction(true); // save.setEnabled(true); //ActionEvent e1;
     * //WindowAdapter source = this; //e1 = new ActionEvent(source,
     * ActionEvent.ACTION_PERFORMED, //	"null"); //save.actionPerformed(e1); //
     * save.(e); // System.exit(0); } // } //} }); //JFrame h=guiFrame; JFrame
     * h=guiFrame;
     *
     * h.setVisible(true);
     *
     * /* PingPoller p2= new PingPoller(ipAddress); p2.pip(ipAddress); String
     * k=p2.pip(ipAddress);
     */
    /*String k="vecc12";
     GraphEditor ob=new GraphEditor(h,k, ipAddress); 
		
     //GraphEditor ob1=new GraphEditor(100);
		
     //guiFrame.setVisible(true);
     }

     @Override
     public void run() {
     //System.out.println("run1");
		 
     // vdi.remove()
		 
		
     while(true)
			
     {
			
			
     System.out.println(r);
	
     //System.out.println("\n");
				
     try{
     /*PingPoller p1= new PingPoller(ipAddress);
     p1.pip();  */
    /**
     * VisibleDifferenceItem iplist= new VisibleDifferenceItem();
     * iplist.add(ipAddress); Thread.sleep(1000); //System.out.println("run2");
     * } catch(InterruptedException e){ e.printStackTrace();
     *
     * }} // TODO Auto-generated method stub
     *
     * }*
     */
    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }catch (Exception e1) {
             System.out.println("Hello");
            e1.printStackTrace();
        }try{
            Statement stmt = DatabaseConnectivity.generateStatement();
            stmt.close();
            GraphEditor editor = new GraphEditor();

            //System.out.println(ipAddress1);
            Runnable r = new Gui(editor);
            Thread t = new Thread(r);
            Runnable r2 = new DeviceCheckingThread(editor);
            //Runnable r2 = new PingIpCheck(editor);
            Thread t2 = new Thread(r2);
            t.start();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
               System.out.println("hello2");
                e.printStackTrace();
            }
            t2.start();
        } catch (Exception e1) {
             System.out.println("Hello");
            e1.printStackTrace();
        }
    }
}
